<template>
    <div>
        <div class="_fc-t-header"> 
            <div class="_fc-t-name">唛盟智能表单</div>
            <div class="_fc-t-menu">
                
                <el-button size="small" type="success" @click="$refs['aiFormDialog'].open()" title="ai输出了表格列信息，黏贴到此组件即可以解析出列信息作为该表单字段">AI导入</el-button> 
                <el-button size="small" type="success" @click="$refs['itemDialog'].open()" title="自动读取数据字典中的下拉列表作为该表单的字段信息">数据字典导入</el-button> 
                <el-button size="small" @click="$refs['dataSetFieldSelectDialog'].open()" type="success"> 数据集导入</el-button>
                <el-button size="small" @click="$refs['tableFieldSelectDialog'].open()" type="success"> 数据表导入</el-button> 
                <el-button size="small" type="danger" @click="showTemplate">生成组件</el-button>
                <el-button size="small" type="primary" @click="saveDesigner">保存</el-button>
            </div>
        </div>
        <fc-designer v-adaptive ref="designer" :locale="locale" height="100%" /> 
        <el-dialog :title="title[type]" v-model="state" class="_fc-t-dialog">
            <div ref="editor" v-if="state"></div>
            <span style="color: red;" v-if="err">输入内容格式有误!</span>
            <template #footer v-if="type > 2">
                <span class="dialog-footer">
            <el-button @click="state = false" size="small">取 消</el-button>
            <el-button type="primary" @click="onOk" size="small">确 定</el-button>
          </span>
            </template>
        </el-dialog>
    </div>
    <mdp-dialog ref="tableFieldSelectDialog" width="90%">
        <template #default="{dialog}">
            <TableFieldSelect  @select="(v)=>{onTableFieldSelect(v);dialog.close();}"/> 
        </template>
    </mdp-dialog>
    
    <mdp-dialog ref="dataSetFieldSelectDialog" width="90%">
        <template #default="{dialog}">
            <DataSetFieldSelect  @select="(v)=>{onTableFieldSelect(v);dialog.close();}"/> 
        </template>
    </mdp-dialog>
    
		<mdp-dialog ref="aiFormDialog">
			<el-form :model="aiForm" ref="aiFormRef"> 
				<el-form-item label="列信息" :rules="{required:true,message:'此项必输',trigger:'blur'}" prop="columnListStr">
					请从Ai输出的表格配置信息中复制黏贴到此
					<el-input rows="20" type="textarea" v-model="aiForm.columnListStr"/>
				</el-form-item>
			</el-form>  
			<el-row class="footer">
				<el-button @click="$refs['aiFormDialog'].close()">关闭</el-button>
				<el-button type="primary" @click="initFormFieldsByAiTable">确定</el-button>
			</el-row>
		</mdp-dialog> 
		<mdp-dialog ref="itemDialog" title="选择数据组" width="80%" :modal="false">
			<template v-slot="{visible,dialog}">
				<mdp-meta-item  :visible="visible" multiple sub-op-type="select" @select="(items)=>{
					dialog.close();
					initFormFieldsByItemCode(items)
				}"/> 
			</template> 
		</mdp-dialog>  
</template>

<script>
import jsonlint from 'jsonlint-mod';
import 'codemirror/lib/codemirror.css';
import 'codemirror/addon/lint/lint.css';
import CodeMirror from 'codemirror/lib/codemirror';
import 'codemirror/addon/lint/lint';
import 'codemirror/addon/lint/json-lint';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/vue/vue';
import 'codemirror/mode/xml/xml';
import 'codemirror/mode/css/css';
import 'codemirror/addon/mode/overlay';
import 'codemirror/addon/mode/simple';
import 'codemirror/addon/selection/selection-pointer';
import 'codemirror/mode/handlebars/handlebars';
import 'codemirror/mode/htmlmixed/htmlmixed';
import 'codemirror/mode/pug/pug';

import is from '@form-create/utils/lib/type';
import formCreate from '@form-create/element-ui';
import ZhCn from "@/plugins/form-create-designer/src/locale/zh-cn";
import En from "@/plugins/form-create-designer/src/locale/en";  
 
import MdpRule from './rule/index.js'; 
 
import TableFieldSelect from '../../dm/meta/TableFieldSelect.vue';
import DataSetFieldSelect from '../../dm/dataSet/FieldSelect.vue';

const TITLE = ['生成规则', '表单规则', '生成组件', '设置生成规则', '设置表单规则'];

export default {
    name: 'app',
    components:{
        TableFieldSelect,DataSetFieldSelect
    },
    data() {
        return {
            state: false,
            value: null,
            title: TITLE,
            editor: null,
            err: false,
            type: -1,
            lang:'cn',
            locale: null,
            expandId:'',
            formDef:null,

            
			aiForm:{
				columnListStr:'',//表格配置信息黏贴
			},  
        };
    },
    watch: {
        state(n) {
            if (!n) {
                this.value = null;
                this.err = false;
            }
        },
        value() {
            this.load();
        },
        $route(to){ 
            if(this.$route.params.expandId){
                this.$mdp.removeFormFieldsCache(this.$route.params.expandId) 
                this.expandId=this.$route.params.expandId
                this.$mdp.listFormDef({id:this.expandId}).then(res=>{
                    var tips=res.tips
                    if(tips.isOk){
                        this.formDef=res.data.length>0?res.data[0]:null 
                        this.$refs.designer.setRule(JSON.parse(this.formDef.rules));
                        this.$refs.designer.setOption(JSON.parse(this.formDef.options));
                    }
                })
            }else{
                this.expandId=''
                this.formDef=null
            }
        }
    },
    methods: {
        
		initFormFieldsByAiTable(){
            
			this.$refs['aiFormRef'].validate(valid=>{
				if(valid==false){
					this.$message.error('表单验证不通过')
					return;
				}else{
                    
                    var rule=this.$refs.designer.getRule(); 
					var columnListStr=this.aiForm.columnListStr
					var datas=columnListStr.split("\n") 
					var columns=datas[0].split("\t")
					var columnIdIdx=columns.findIndex(k=>k.indexOf('列名')>=0)
					var columnTypeIdx=columns.findIndex(k=>k.indexOf('数据类型')>=0)
					var columnRemarkIdx=columns.findIndex(k=>k.indexOf('描述')>=0)
					var columList=datas.slice(1); 
					var rls=columList.map(k=>{
						var c=k.split("\t")
						var field={type:'input',field:c[columnIdIdx],title:c[columnRemarkIdx]} 
                        return field
 					}) 
                    if(rls.length==0){
                        this.$message.error('没有解析到相关字段信息')
                        return;
                    }
                    rule.push(...rls)
                    this.$refs.designer.setRule(rule); 
				}
			})  
		},
		initFormFieldsByItemCode(items){ 
            var rule=this.$refs.designer.getRule(); 
            if(items!=null && items.length>0){
                var rls=items.map(k=>{
                    var rl={type:'MdpSelect',props:{itemCode:k.itemCode},title:k.itemName,field:this.$mdp.toCamel(k.itemCode)}
                    return rl
                }) 
                rule.push(...rls)
                this.$refs.designer.setRule(rule); 
            } 
		},
        onTableFieldSelect(dmFields){
            var rule=this.$refs.designer.getRule(); 
            if(dmFields!=null && dmFields.length>0){
                var rls=dmFields.map(k=>{
                    var rl={type:'input',title:k.remarks,field:this.$mdp.toCamel(k.columnName)}
                    return rl
                }) 
                rule.push(...rls)
                this.$refs.designer.setRule(rule); 
            } 
        },
        changeLocale() {
            if (this.lang === 'cn') {
                this.locale = En;
                this.lang = 'en';
            } else {
                this.locale = ZhCn;
                this.lang = 'cn';
            }
        },
        load() {
            let val;
            if (this.type === 2) {
                val = this.value;
            } else if (this.type === 0) {
                val = formCreate.toJson(this.value, 2);
            } else {
                val = JSON.stringify(this.value, null, 2);
            }
            this.$nextTick(() => {
                this.editor = CodeMirror(this.$refs.editor, {
                    lineNumbers: true,
                    mode: this.type === 2 ? {name: 'vue'} : 'application/json',
                    gutters: ['CodeMirror-lint-markers'],
                    // lint: true,
                    line: true,
                    tabSize: 2,
                    lineWrapping: true,
                    value: val || ''
                });
            });
        },
        onValidationError(e) {
            this.err = e.length !== 0;
        },
        showJson() {
            this.state = true;
            this.type = 0;
            this.value = this.$refs.designer.getRule();
        },
        saveDesigner(){
            var rule=this.$refs.designer.getRule(); 
            var option=this.$refs.designer.getOption();   
            var formDef={
                id: this.expandId,
                formName: option.form.formName, 
                rules:JSON.stringify(rule).replace(/\$/g,''),
                options:JSON.stringify(option).replace(/\$/g,'')
            }
            if(!option.form.formName){
                this.$message({message:'请设置表单名称'})
                return;
            }
            var func=this.$mdp.addFormDef
            if(this.expandId){
                func=this.$mdp.editFormDef
            }
            func(formDef).then(res=>{  
                this.$message({position:'bottom-left',showClose:true,message: res.tips.msg, type: res.tips.isOk?'success':'error' });
                if(!this.expandId){
                    this.$router.push({path:"/mdp/form/design/edit/"+res.data.id})
                } 
            })
        },
        showOption() {
            this.state = true;
            this.type = 1;
            this.value = this.$refs.designer.getOption();
        },
        showTemplate() {
            this.state = true;
            this.type = 2;
            this.value = this.makeTemplate();
        },
        setJson() {
            this.state = true;
            this.type = 3;
            this.value = [];
        },
        setOption() {
            this.state = true;
            this.type = 4;
            this.value = {form: {}};
        },
        onOk() {
            if (this.err) return;
            const json = this.editor.getValue();
            let val = JSON.parse(json);
            if (this.type === 3) {
                if (!Array.isArray(val)) {
                    this.err = true;
                    return;
                }
                this.$refs.designer.setRule(formCreate.parseJson(json));
            } else {
                if (!is.Object(val) || !val.form) {
                    this.err = true;
                    return;
                }
                this.$refs.designer.setOption(val);
            }
            this.state = false;
        },
        makeTemplate() {
            const rule = this.$refs.designer.getRule();
            const opt = this.$refs.designer.getOption();
            return `<template>
  <form-create
    v-model="fapi"
    :rule="rule"
    :option="option"
    @submit="onSubmit"
  ></form-create>
</template>

<script>
import formCreate from "@form-create/element-ui";

export default {
  data () {
    return {
        fapi: null,
        rule: formCreate.parseJson('${formCreate.toJson(rule).replaceAll('\\', '\\\\')}'),
        option: formCreate.parseJson('${JSON.stringify(opt)}')
    }
  },
  methods: {
    onSubmit (formData) {
      //todo 提交表单
    }
  }
}
<\/script>`;
        }
    },
    beforeCreate() {
        window.jsonlint = jsonlint;
    },  
    created(){
    },
    mounted() { 
        if(this.$route.params.expandId){
            this.$mdp.removeFormFieldsCache(this.$route.params.expandId)
            this.expandId=this.$route.params.expandId
            this.$mdp.listFormDef({id:this.expandId}).then(res=>{
                var tips=res.tips
                if(tips.isOk){
                    this.formDef=res.data.length>0?res.data[0]:null
                    this.$refs.designer.setRule(JSON.parse(this.formDef.rules));
                    this.$refs.designer.setOption(JSON.parse(this.formDef.options));
                }
            })
        }else{
            this.expandId=''
            this.formDef=null
        }

        MdpRule.install(this.$refs.designer)  
 
    }
};

</script>

<style>
._fc-t-header {  
    position: relative;
    display: flex;
    align-items: center;
    cursor: default;
}

._fc-t-logo {
    height: 26px;
}

._fc-t-name {
    display: inline-block;
    color: rgba(0, 0, 0, 0.8);
    font-size: 20px;
    font-weight: 600;
    margin-left: 5px;
}

._fc-t-menu {
    position: absolute;
    right: 0;
}

._fc-t-menu i {
    font-size: 12px;
}

body {
    min-height: 100vh;
    padding: 0;
    margin: 0;
    display: flex !important;
    flex-direction: column !important;
}

#app {
    display: flex;
    flex-direction: column;
    flex: 1;
}

._fc-copyright {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 20px;
    font-size: 16px;
    border-top: 1px solid #ECECEC;
    background-color: #fff;
    cursor: pointer;
}

._fc-t-dialog .CodeMirror {
    height: 450px;
}

._fc-t-dialog .CodeMirror-line {
    line-height: 16px !important;
    font-size: 13px !important;
}

.CodeMirror-lint-tooltip {
    z-index: 2021 !important;
}

._fc-t-dialog .el-dialog__body {
    padding: 0px 20px;
}

._fc-b-item {
    display: flex;
}

</style>
